/*  header-comment
/*  file   : /Users/arida/react-hrm-h5/src/components/Upload/index
/*  author : arida
/*  date   : 2017-6-4 18:27:31
/*  last   : 2017-9-1 10:42:19
*/
import React, { Component } from "react";
import PropTypes from "prop-types";
import lrz from "lrz"; // 用于图片压缩,库大小32kb

import { alert } from "../../utils/dingtalk";
import lwp from "../../utils/lwp";
import { get } from "../../utils/db.js";
import fetch from "../../utils/fetch.js";

import "./index.less";

const IMG_EXTENSION = "image/gif,image/jpeg,image/jpg,image/png,image/svg";
const pdfSurface =
  "https://gw.alicdn.com/tfs/TB1ODTxggMPMeJjy1XbXXcwxVXa-210-210.png";

/**
 * 判断传入的文件是否可以接受（即是否允许上传）
 * @param {*} file 
 * @param {*} acceptList 
 * @return {} 是否通过
 */
function accept(file, acceptList) {
  if (!file) return false;
  if (acceptList.indexOf(file.type) === -1) return false;

  return true;
}
function isImage(file) {
  return IMG_EXTENSION.split(",").indexOf(file.type) !== -1;
}

/**
 * 上传组件
 * 基于input tyle=file的封装,用于图片上传  
 */
class Upload extends Component {
  constructor(props) {
    super(props);
    this.handleFileChange = this.handleFileChange.bind(this);
  }
  static defaultProps = {
    // 接受的文件类型,注意不能写image/*，否则webkit会遍历所有并校验，会很卡（貌似是bug）
    accept: IMG_EXTENSION.concat(",application/pdf"),
    options: {
      quality: 0.3 // 如果需要调整压缩比率，请改变这个参数
    },
    onChange: () => null,
    onFileChange: () => null
  };
  static propTypes = {
    accept: PropTypes.string,
    options: PropTypes.shape({
      width: PropTypes.number,
      height: PropTypes.number,
      quality: PropTypes.number,
      fieldName: PropTypes.string
    }),
    type: PropTypes.number,
    children: PropTypes.element,
    handleFileChangeByTakePhoto: PropTypes.func,
    onFileChange: PropTypes.func, // 返回 Object {formData: formData, url: 'base64'}
    onChange: PropTypes.func
  };
  handleFileChange() {
    const files = this.refs["renliwo-dingding"].files;
    const file = files[0];

    if (!file) return;

    if (!accept(file, this.props.accept.split(","))) {
      return alert({title: "出错了", message: "目前不支持此格式的文件噢～"});
    }
    const size = file.size;
    if (size > 10 * 1024 * 1024) {
      return alert({title: "出错了", message: "图片太大了,请上传10MB以内的文件"});
    }
    if (isImage(file)) {
      lrz(file, this.props.options).then(q => {
        const exifdata = q.origin.exifdata;
        const { PixelYDimension = 0, PixelXDimension = 0 } = exifdata;

        const _file = {
          formData: q.formData,
          url: q.base64,
          direction:
            PixelXDimension >= PixelYDimension ? "horizontal" : "vertical"
        };

        this.props.onFileChange(_file);
        this.props.onChange(_file.url);
      });
    } else {
      // 上传其他类型文件，在这里指的是pdf
      const formData = new FormData();
      formData.append("file", file);
      this.props.onFileChange({
        formData: formData,
        url: pdfSurface
      });
      this.props.onChange(pdfSurface);
    }
  }

  //获取公钥
  getPublicKey(){
      const lwpPublicKeyUrl = "/r/Adaptor/HRMCommonI/getPublicKey";
      const data = [
        get('corpId')
      ]
      return new Promise((resolve, reject) => {
        lwp(lwpPublicKeyUrl, { body: data }).then((result) => {
          let text = '';
          try {
            text = JSON.parse(result.responseText)
          } catch (error) {
            text = result.responseText;
          }
          resolve(text)
        });
      })
  }

  

  /**
   * 获取真实的图片地址（一次性访问）
   * @param {*Array} fileKey 
   */
  getRealFileUrl(fileKey) {
    return new Promise((resolve, reject) => {
      fetch(`/hrmregister/mobile/emp/getAccessURLByEncryptedFileKeys`, {
        body: fileKey,
        meta: {
          dipId: "",
          silence: true
        }
      }).then(res => {
        if (res && res.success) {
          //这里只取第一个
          resolve(res.result && res.result[0]);
        }else{
          resolve("");
        }
      }).catch((error)=>{
      });
    })
  }

  //调用jsapi拍摄身份证
  async takePhoto() {
    const t = this;
    const publicKey = await this.getPublicKey();
    const lwpGetCardFileKey = "/r/Adaptor/HRMCommonI/uploadFileByUrl";
    if (!publicKey) return;
    //type = 1 正面 2反面
    const type = this.props.type;
    // console.log("use takePhoto");
    //调用jsapi接口拍照 
    const versonFlag = dd.compareVersion("3.5.3", dd.version);//是否大于3.5.6
    if (!versonFlag) {
      alert({ message: "版本过低，请升级钉钉客户端" });
      return;
    }
    dd.biz.verify.takePhoto({
      type: type,
      publicKey: publicKey,
    }).then((result) => {
      const data = [
        get('corpId'),
        result.image,
        result.encryptedAESKey,
        result.initVector
      ]
      lwp(lwpGetCardFileKey, { body: data }).then((rKeys) => {
        try {
          let text = "";
          try {
            text = JSON.parse(rKeys.responseText);
          } catch (error) {
            text = rKeys.responseText
          }
          if (!text) return
          fetch(`/hrmregister/mobile/emp/getAccessURLByEncryptedFileKeys`, {
            body: [].concat(text),
            meta: {
              dipId: "",
              silence: true
            }
          }).then(res => {
            if (res && res.success) {
              //这里只取第一个
              const url = res.result && res.result[0];
              const _file = {
                formData: null,
                url: url,
                direction: "horizontal",
              };
              t.props.handleFileChangeByTakePhoto(_file, text);
            }
          }).catch(()=>{
          })
        } catch (error) {
            alert({ message: '出现错误，请重试' });
        }
      })
    })

  }
  render() {
    const type = this.props.handleFileChangeByTakePhoto;
    return (
      <div>
        {this.props.children}
        {
          type ? <div className="upload-takePhoto" onClick={() => this.takePhoto()}></div>
            : <input
              ref="renliwo-dingding"
              className="renliwo-design-upload"
              type="file"
              accept={this.props.accept}
              onChange={this.handleFileChange}
            />
        }

        {/* <input
          ref="renliwo-dingding"
          className="renliwo-design-upload"
          type="file"
          accept={this.props.accept}
          onChange={this.handleFileChange}
        /> */}
      </div>
    );
  }
}

export default Upload;
